import { axios } from "./../../utils/request"
// pages/userEditor/userEditor.ts
Page({
  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: "",
    nickName: "",
    gender: "",
    genderList: [
      { name: "男", value: "1" },
      { name: "女", value: "0" },
    ],
    show: false,
  },
  async init() {
    let userInfo = wx.getStorageSync("userInfo")
    let { avatarUrl, nickName, gender } = userInfo
    this.setData({
      avatarUrl,
      nickName,
      gender,
    })
  },
  onChange(e: any) {
    const value = e.detail
    this.setData({
      name: value,
    })
  },
  async chooseAvatar() {
    try {
      let fileData = await wx.chooseMedia({
        count: 1,
        mediaType: ["image"],
        sourceType: ["album", "camera"],
        camera: "front",
      })
      let tempPath = fileData.tempFiles[0].tempFilePath
      wx.showToast({
        title: "正在上传",
        icon: "loading",
      })
      wx.uploadFile({
        url: "https://www.tinyxu.fun/v1/user/avatar",
        filePath: tempPath,
        header: { Authorization: "Bearer " + wx.getStorageSync("token") },
        name: "avatar",
        success: (res: any) => {
          let userInfo = JSON.parse(res.data).data[0]
          wx.setStorageSync("userInfo", userInfo)
          this.init()
          wx.hideLoading()
        },
      })
    } catch (error) {
      wx.showToast({
        title: "上传失败",
        icon: "none",
      })
    }
  },
  toNickName() {
    wx.navigateTo({
      url: "/pages/nickname/nickname",
    })
  },
  showGender() {
    this.setData({
      show: true,
    })
  },
  closeGender() {
    this.setData({
      show: false,
    })
  },
  async confirmGender(e: any) {
    let gender = e.detail.value.value
    let result = (await axios("/user/gender", "POST", { gender })) as any
    let userInfo = result.data[0]
    wx.setStorageSync("userInfo", userInfo)
    this.setData({
      show: false,
    })
    this.init()
    wx.showToast({
      title: "修改成功",
      icon: "success",
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow() {
    this.init()
  },
})
